import router, { asyncRoutes } from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import getPageTitle from '@/utils/get-page-title'

// 前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  document.title = getPageTitle(to.meta.title)
  const token = store.state.user.token
  const whiteList = ['/login', '/404']
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 判断用户信息是否已经获取,获取过就不需要再获取
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        console.log(menus, '用户页面级别的权限数据')
        console.log(asyncRoutes, '{asyncRoutes}')
        // 使用权限信息筛选出用户可以访问的动态路由
        const filterRoutes = asyncRoutes.filter(route => {
          return menus.includes(route.children[0].name)
        })
        console.log(filterRoutes)
        // 渲染左侧菜单 需要权限的信息,根据权限信息动态的添加路由
        // 动态的添加用户可以访问的路由
        router.addRoutes(filterRoutes)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
// 后置守卫
router.afterEach(() => {
  NProgress.done()
})
